package com.baosight.sczx.zm.cp.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.StaticBlocks;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.Department;
import com.baosight.sczx.common.zm.cInterface.cp.ProducePlan;
import com.baosight.sczx.common.zm.cInterface.cp.ProfessionalPlan;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.common.zm.cInterface.cs.WorkingFace;
import com.baosight.sczx.zm.cp.domain.ZMCPProducePlanCM;

/**
 * 采煤计划明细表
 * @author wealupa
 * By.严洪浩
 */
public class ServiceZMCP11 extends ServiceEPBase {
	
	/**
	 * 初始化进入
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		inInfo.addBlock(EiConstant.resultBlock).set(EiConstant.limitStr, "100");//设置每页默认显示记录数
		EiInfo outInfo = this.query(inInfo);
		return outInfo;
	}
	
	/**
	 * 查询
	 */
	@Override
	public EiInfo query(EiInfo inInfo) {
		
		String fdProfessionalplanId = inInfo.getString("fdProfessionalplanId");
		String fdProduceplanId = inInfo.getString("fdProduceplanId");
		
		if(fdProfessionalplanId != null) {
			StaticTools.setQueryParameters(inInfo, "fdProfessionalplanId", inInfo.getString("fdProfessionalplanId"), true);//添加查询条件
			StaticTools.setQueryParameters(inInfo, "isProfessionalplan", "任意数值", true);
		}

		if(fdProduceplanId != null) {
			StaticTools.setQueryParameters(inInfo, "fdProduceplanId", inInfo.getString("fdProduceplanId"), true);//添加查询条件
		}
		
		if(fdProfessionalplanId == null && fdProduceplanId == null) {
			return inInfo;
		}

		EiInfo outInfo = super.query(inInfo, "ZMCPProducePlanCM.query", new ZMCPProducePlanCM());		

		outInfo.addBlock(Department.getInstance().getMiningDepts("cmes.cp.department", "orgCode", "orgName", true, UserSession.getInSessionProperty("miningCode").toString()));
		outInfo.addBlock(WorkingFace.getMiningWorkingFace("cmes.cp.workingface", true, UserSession.getInSessionProperty("miningCode").toString()));
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.recoveryProcess", true));//落煤方式
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cp.qualityGrade", true));//质量等级
		outInfo.addBlock(StaticBlocks.getPlanMonth("cmes.cp.planMonth", true));
		outInfo.addBlock(StaticBlocks.getPlanStatus("cmes.cp.planStatus", true));
		
		return outInfo;
	}
	
	/**
	 * 新增采煤计划明细
	 * 主表不等于草拟状态，不能新增
	 */
	@Override	
	public EiInfo insert(EiInfo inInfo) {
		//校验是否重复
	
		EiInfo out = new EiInfo(); 
		String fdPlanYear = inInfo.getString("fdPlanYear");
		String fdPlanMonth = inInfo.getString("fdPlanMonth");
		String fdProfessionalplanId = inInfo.getString("fdProfessionalplanId");
		String fdProduceplanId = inInfo.getString("fdProduceplanId");
		
		if(fdProfessionalplanId == null && fdProduceplanId == null)
			return inInfo;
		
		boolean checkProfessionalPlan = ProfessionalPlan.validate(fdProfessionalplanId);
		if(!checkProfessionalPlan) {
			out = this.query(inInfo);
			out.setMsg("当月的采煤专业计划已经上报或作废，不能新增！");
			return out;
		}
		
		boolean checkProducePlan = ProducePlan.validate(fdProduceplanId);
		if(!checkProducePlan) {
			out = this.query(inInfo);
			out.setMsg("当月的生产计划已经发布，不能新增！");
			return out;
		}
		
		ZMCPProducePlanCM _dom = new ZMCPProducePlanCM();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		boolean needUpdate = false;
		
		for (int i = 0; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			Map<String, String> params = new HashMap<String, String>();
			if(fdProfessionalplanId != null && !fdProfessionalplanId.trim().equals("")) {
				params.put("fdProfessionalplanId", fdProfessionalplanId);
			}
			if(fdProduceplanId != null && !fdProduceplanId.trim().equals("")) {
				params.put("fdProduceplanId", fdProduceplanId);
			}
			params.put("fdPlanYear", fdPlanYear);
			params.put("fdPlanMonth", fdPlanMonth);
			params.put("fdProjectId", _dom.getFdProjectId());
			params.put("fdDepartmentId", _dom.getFdDepartmentId());
			boolean validate = this.validate(inInfo, "ZMCPProducePlanCM.validate", params);
			if(validate) 
			{
				return inInfo;
			} 
			else{
				_dom.setFdProfessionalplanId(fdProfessionalplanId);
				_dom.setFdProduceplanId(fdProduceplanId);
				
				_dom.setFdDepartment(Department.getInstance().getDepartmentNameById(_dom.getFdDepartmentId()));		//施工单位名称
				_dom.setFdCreateDepartmentId(UserSession.getInSessionProperty("orgCode").toString());				//创建部门ID
				_dom.setFdCreateDepartment(UserSession.getInSessionProperty("orgName").toString());
				_dom.setFdCreatorId(UserSession.getUserId().toString());
				_dom.setFdCreator(UserSession.getInSessionProperty("UserCname").toString());
				_dom.setFdPlanYear(inInfo.getString("fdPlanYear"));
				_dom.setFdPlanMonth(inInfo.getString("fdPlanMonth"));
				_dom.setFdCreattime(StaticTools.getDateTime());
				_dom.setFdKeyId(TablePk.getInstance().getNextValue("T_CP_PRODUCEPLAN_CM"));
				int DayNum = StaticTools.getMonthDayNum(Integer.parseInt(fdPlanYear), Integer.parseInt(fdPlanMonth));
				int big = _dom.getFdPlanSum().intValue();
				_dom.setFdDaySum(new BigDecimal(big/DayNum));
				dao.insert("ZMCPProducePlanCM.insert", _dom);
				
				needUpdate = true;
		    }
		}
		
		if (needUpdate) {
			//只需更新专业计划主表的采煤相关数据
			//无需更新生产计划主表的数据
			
			if(fdProfessionalplanId != null  && !fdProfessionalplanId.trim().equals("")) {
				ProfessionalPlan.updateByCM(fdProfessionalplanId);
			}
			else if (fdProduceplanId != null && !fdProduceplanId.trim().equals("")){
				ProducePlan.updateByCM(fdProduceplanId, null, 0);
			}
		}

		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out;  
	}

	/**
	 * 修改采煤计划明细
	 * 主表不等于草拟状态，不能修改
	 */
	@Override	
	public EiInfo update(EiInfo inInfo) {
		//校验是否重复
	
		EiInfo out = new EiInfo(); 
		String fdProfessionalplanId = inInfo.getString("fdProfessionalplanId");
		String fdProduceplanId = inInfo.getString("fdProduceplanId");
		
		if(fdProfessionalplanId == null && fdProduceplanId == null)
			return inInfo;
		
		boolean checkProfessionalPlan = ProfessionalPlan.validate(fdProfessionalplanId);
		if(!checkProfessionalPlan) {
			out = this.query(inInfo);
			out.setMsg("当月的采煤专业计划已经上报或作废，不能修改！");
			return out;
		}
		
		boolean checkProducePlan = ProducePlan.validate(fdProduceplanId);
		if(!checkProducePlan) {
			out = this.query(inInfo);
			out.setMsg("当月的生产计划已经发布，不能修改！");
			return out;
		}
		
		ZMCPProducePlanCM _dom = new ZMCPProducePlanCM();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		boolean needUpdate = false;
		
		for (int i = 0; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			Map<String, String> params = new HashMap<String, String>();
			if(fdProfessionalplanId != null && !fdProfessionalplanId.trim().equals("")) {
				params.put("fdProfessionalplanId", fdProfessionalplanId);
			}
			if(fdProduceplanId != null && !fdProduceplanId.trim().equals("")) {
				params.put("fdProduceplanId", fdProduceplanId);
			}
			params.put("fdKeyId", _dom.getFdKeyId());
			params.put("fdPlanYear", _dom.getFdPlanYear());
			params.put("fdPlanMonth", _dom.getFdPlanMonth());
			params.put("fdProjectId", _dom.getFdProjectId());
			params.put("fdDepartmentId", _dom.getFdDepartmentId());
			boolean validate = this.validate(inInfo, "ZMCPProducePlanCM.validate", params);
			if(validate) 
			{
				return inInfo;
			} 
			else{
				_dom.setFdDepartment(Department.getInstance().getDepartmentNameById(_dom.getFdDepartmentId()));		//施工单位名称
				
				int DayNum = StaticTools.getMonthDayNum(Integer.parseInt(_dom.getFdPlanYear()), Integer.parseInt(_dom.getFdPlanMonth()));
				int big = _dom.getFdPlanSum().intValue();
				_dom.setFdDaySum(new BigDecimal(big/DayNum));
				_dom.setFdCreattime(StaticTools.getDateTime());

				dao.update("ZMCPProducePlanCM.update", _dom);
				
				needUpdate = true;
		    }
		}
		
		if (needUpdate) {
			//只需更新专业计划主表的采煤相关数据
			//无需更新生产计划主表的数据
			if(fdProfessionalplanId != null && !fdProfessionalplanId.trim().equals("")) {
				ProfessionalPlan.updateByCM(fdProfessionalplanId);
			}
			else if (fdProduceplanId != null && !fdProduceplanId.trim().equals("")){
				ProducePlan.updateByCM(fdProduceplanId, null, 0);
			}
		}

		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out;  
	}
	
	/**
	 * 删除采煤计划明细
	 * 主表不等于草拟状态，不能修改
	 */
	@Override	
	public EiInfo delete(EiInfo inInfo) {
		
		EiInfo _temp = new EiInfo();
		
		String fdProfessionalplanId = inInfo.getString("fdProfessionalplanId");
		String fdProduceplanId = inInfo.getString("fdProduceplanId");
		
		if(fdProfessionalplanId == null && fdProduceplanId == null)
			return inInfo;
		
		boolean checkProfessionalPlan = ProfessionalPlan.validate(fdProfessionalplanId);
		if(!checkProfessionalPlan) {
			_temp = this.query(inInfo);
			_temp.setMsg("当月的采煤专业计划已经上报或作废，不能删除！");
			return _temp;
		}
		
		boolean checkProducePlan = ProducePlan.validate(fdProduceplanId);
		if(!checkProducePlan) {
			_temp = this.query(inInfo);
			_temp.setMsg("当月的生产计划已经发布，不能删除！");
			return _temp;
		}
		
		_temp = super.delete(inInfo, "ZMCPProducePlanCM.delete");
		
		//只需更新专业计划主表的采煤相关数据
		//无需更新生产计划主表的数据

		if(fdProfessionalplanId != null && !fdProfessionalplanId.trim().equals("")) {
			ProfessionalPlan.updateByCM(fdProfessionalplanId);
		}
		else if (fdProduceplanId != null && !fdProduceplanId.trim().equals("")){
			ProducePlan.updateByCM(fdProduceplanId, null, 0);
		}
		
		EiInfo outInfo = this.query(inInfo);
        outInfo.setMsg(_temp.getMsg());
        outInfo.setDetailMsg(_temp.getDetailMsg());
		outInfo.setStatus(1);

		return outInfo;  
	}
	
	/**
	 * 退回数据
	 * @param inInfo
	 * @return
	 */
	public EiInfo revert(EiInfo inInfo) {
		EiInfo out = new EiInfo();
		String fdProduceplanId = inInfo.getString("fdProduceplanId");
		String message = "";
		
		//1.0判断生产计划是否生效
		if(fdProduceplanId != null && !fdProduceplanId.equals("")) {
			Map<String, String> _map = new HashMap<String, String>();
			_map.put("fdKeyId", fdProduceplanId);
			_map.put("fdPlanStatus", "草拟");
			boolean check = ProducePlan.validate(_map);
			
			if(!check) {
				out = this.query(inInfo);
				out.setStatus(-1);
				out.setMsg("所选择记录对应的月度计划不是草拟状态，不能退回！");
				return out;  
			}
		}
		else {
			out = this.query(inInfo);
			out.setStatus(1);
			return out;  
		}
		
		ZMCPProducePlanCM _dom = new ZMCPProducePlanCM();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
	
		List<String> revertList = new ArrayList<String>();
		
		for (int i = 0; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			
			String fdProfessionalplanId = _dom.getFdProfessionalplanId();
			
			//2.0不是上报的，是自己新增的
			if(fdProfessionalplanId == null || fdProfessionalplanId.trim().equals("")) {
				message = "所选数据中有不是专业计划上报的，不能退回";
				continue;
			}
			if(!revertList.contains(fdProfessionalplanId)) {
				revertList.add(fdProfessionalplanId);
			}
		}
		
		//2.0删除生产计划数据，根据专业计划ID
		for(int i = 0; i < revertList.size(); i++) {
			String fdProfessionalplanId = revertList.get(i);
			Map<String, String> _map = new HashMap<String, String>();			
			_map.put("fdProfessionalplanId", fdProfessionalplanId);
			
			int result = this.dao.delete("ZMCPProducePlanCM.revert", _map);
			
			//3.0修改专业计划状态，根据专业计划ID
			if(result > 0) {
				_map.put("fdPlanStatus", "上报");
				_map.put("fdKeyId", fdProfessionalplanId);
				ProfessionalPlan.revert(_map);
			}
		}
		
		//4.0更新生产计划总数值
		ProducePlan.updateByCM(fdProduceplanId, revertList, 2);
		
		out = this.query(inInfo);
		if(message.equals("")) {
			out.setStatus(1);
			out.setMsg("操作" + rowcount + "记录成功");
		}
		else {
			out.setStatus(-1);
			out.setMsg(message);
		}
		return out;  
	}
	
	/**
	 * 验证每月只能一条记录
	 * @param inInfo
	 * @param _dom
	 * @param sqlName
	 * @param params
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private boolean validate(EiInfo inInfo, String sqlName, Map<String, String> params) {
		if(params == null) {
			params = new HashMap<String, String>();
		}
		List result = dao.query(sqlName, params);
		if(result != null && result.size() > 0) {
			inInfo.setStatus(-1);
			String msg = "采煤计划每月同一施工部门针对同一工作面只能新增一条记录！";
			inInfo.setMsg(msg);
			return true;
		}
		return false;
	}
}
